package com.cbs.android.module.userkit.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.applicationutils.network.ErrorResponse;
import com.cbs.android.component.log.L;
import com.cbs.android.component.sms.smsinterface.SmsHandler;
import com.cbs.android.component.toast.Toast;
import com.cbs.android.module.user.user.UserModule;
import com.cbs.android.module.user.user.entity.User;
import com.cbs.android.module.user.user.handler.ModuleHandler;
import com.cbs.android.module.userkit.R;
import com.cbs.android.widget.countdownview.CountDownView;
import com.cbs.android.widget.loadingframelayout.LoadingFrameLayout;
import com.google.gson.Gson;

/**
 * Created by broche on 10/30/15.
 */
public class RegisterActivity extends CBSActivity implements View.OnClickListener {
    private static final String TAG = RegisterActivity.class.getName();
    private static final int PasswordLength = 6;
    private static final int VerifyCodeRetryInterval = 60;

    private EditText userNameView;
    private EditText passwordView;
    private EditText passwordView2;
    private EditText verifyCodeView;
    private LoadingFrameLayout loadingView;
    private CountDownView getVerifyCodeView;
    private CheckBox agreeView;

    protected boolean needPwd2() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setResult(RESULT_CANCELED);

        super.setContentView(R.layout.cbs_userkit_activity_register);
        userNameView = (EditText) findViewById(R.id.cbs_userkit_register_username);
        passwordView = (EditText) findViewById(R.id.cbs_userkit_register_password);
        passwordView2 = (EditText) findViewById(R.id.cbs_userkit_register_password2);
        verifyCodeView = (EditText) findViewById(R.id.cbs_userkit_register_verifycode);
        loadingView = (LoadingFrameLayout) findViewById(R.id.cbs_userkit_register_loading);
        getVerifyCodeView = (CountDownView) findViewById(R.id.cbs_userkit_register_getverifycode);
        agreeView = (CheckBox) findViewById(R.id.cbs_userkit_register_agree);

        findViewById(R.id.cbs_userkit_register_back).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_register_getverifycode).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_register_submit).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_register_agreement).setOnClickListener(this);

        if (needPwd2()) {
            passwordView2.setVisibility(View.VISIBLE);
        } else {
            passwordView2.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.cbs_userkit_register_back) {
            finish();
        } else if (v.getId() == R.id.cbs_userkit_register_getverifycode) {
            String username = userNameView.getText().toString().trim();
            if (username.length() != 11) {
                Toast.show(getString(R.string.cbs_userkit_verify_invalidusernamelength));
                return;
            }

            getVerifyCodeView.start(VerifyCodeRetryInterval * 1000, new CountDownView.CountDownListener() {
                @Override
                public void onFinish(CountDownView countDownView) {
                    countDownView.setEnabled(true);
                }
            });
            v.setEnabled(false);
            UserModule.checkUser(username, new ModuleHandler<Boolean>() {
                @Override
                public void onSuccess(Boolean entity) {
                    if (entity) {
                        Toast.show(getString(R.string.cbs_userkit_verify_existed));
                        getVerifyCodeView.stop();
                        getVerifyCodeView.setEnabled(true);
                    } else {
                        UserModule.sendSmsCode(userNameView.getText().toString(), new SmsHandler() {
                            @Override
                            public void onSent() {
                                // do nothing
                            }

                            @Override
                            public void onCodeReceived(String code) {
                                // do nothing
                            }

                            @Override
                            public void onFailure(int code, String message) {
                                Toast.show(message);
                                getVerifyCodeView.stop();
                                getVerifyCodeView.setEnabled(true);
                            }
                        });

                        Toast.show(getString(R.string.cbs_userkit_hint_smsSent));
                    }
                }

                @Override
                public void onFailure(int code, String message) {
                    L.w(TAG, "code: " + code + "\tmessage: " + message);
                    getVerifyCodeView.stop();
                    getVerifyCodeView.setEnabled(true);
                }

                @Override
                public void onException(Exception exception) {
                    L.w(TAG, "", exception);
                    getVerifyCodeView.stop();
                    getVerifyCodeView.setEnabled(true);
                }
            });
        } else if (v.getId() == R.id.cbs_userkit_register_submit) {
            String username = userNameView.getText().toString().trim();
            if (username.length() != 11) {
                Toast.show(getString(R.string.cbs_userkit_verify_invalidusernamelength));
                return;
            }
            String verifyCode = verifyCodeView.getText().toString().trim();
            if (verifyCode.length() < 1) {
                Toast.show(getString(R.string.cbs_userkit_verify_invalidverifycodelength));
                return;
            }
            String pwd1 = passwordView.getText().toString();
            String pwd2 = passwordView2.getText().toString();
            if (needPwd2()) {
                if (!pwd1.equals(pwd2)) {
                    Toast.show(getString(R.string.cbs_userkit_verify_differentpassword));
                    return;
                } else if (pwd1.equals("") || pwd2.equals("")) {
                    Toast.show(getString(R.string.cbs_userkit_verify_emptypassword));
                    return;
                } else if (pwd1.length() < PasswordLength || pwd2.length() < PasswordLength) {
                    Toast.show(getString(R.string.cbs_userkit_verify_shortpassword));
                    return;
                }
            } else {
                if (pwd1.equals("")) {
                    Toast.show(getString(R.string.cbs_userkit_verify_emptypassword));
                    return;
                } else if (pwd1.length() < PasswordLength) {
                    Toast.show(getString(R.string.cbs_userkit_verify_shortpassword));
                    return;
                }
            }
            if (!agreeView.isChecked()) {
                Toast.show(getString(R.string.cbs_userkit_verify_agreement));
                return;
            }

            loadingView.startLoading();
            UserModule.register(userNameView.getText().toString().trim(), passwordView.getText().toString(), verifyCodeView.getText().toString().trim(), new ModuleHandler<User>() {
                @Override
                public void onSuccess(User entity) {
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                public void onFailure(int code, String message) {
                    try {
                        ErrorResponse errorResponse = new Gson().fromJson(message, ErrorResponse.class);
                        Toast.show(errorResponse.getErrorMsg());
                    } catch (Exception e) {
                        // TODO what to do
                    }
                    loadingView.stopLoading();
                    L.w(TAG, "code: " + code + "\tmessage: " + message);
                }

                @Override
                public void onException(Exception exception) {
                    loadingView.stopLoading();
                    Toast.show(getString(R.string.cbs_userkit_hint_register_unknow));
                    L.w(TAG, "", exception);
                }
            });
        } else if (v.getId() == R.id.cbs_userkit_register_agreement) {
            // TODO open webview
        }
    }
}
